package com.system.common.controller;

import com.system.common.constant.BaseEnum;
import com.system.common.constant.SessionKeyConst;
import com.system.common.request.person.LoginReq;
import com.system.common.response.BaseResp;
import com.system.common.response.PageResp;
import com.system.common.service.persion.PersonService;
import com.system.common.service.purview.PurviewService;
import com.system.common.service.role.RoleService;
import com.system.common.vo.person.LoginVo;
import com.system.common.vo.person.PersonVo;
import com.system.common.vo.purview.PurviewVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
public class IndexController {

    public static final String LOGIN_UI = "/admin/login";

    @Autowired
    private PersonService personService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PurviewService purviewService;

    @RequestMapping(value = "/admin/index", method = {RequestMethod.GET})
    public String index(){
        return "/admin/index";
    }


    @RequestMapping(value = LOGIN_UI, method = {RequestMethod.GET})
    public String login(HttpServletRequest request, HttpServletResponse response){
        cleanLoginInfo(request);
        return LOGIN_UI;
    }

    @RequestMapping(value = "/admin/doLogin", method = RequestMethod.POST)
    @ResponseBody
    public BaseResp doLogin(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody LoginReq loginReq){

        HttpSession session = request.getSession();
        // 删除上次登陆信息
        cleanLoginInfo(request);
        String imageCode = (String) session.getAttribute(SessionKeyConst.CAPTCHA_ADMIN_KEY);
        if(StringUtils.isBlank(imageCode) || StringUtils.isBlank(loginReq.getImageCode())){
            BaseResp resp = new BaseResp();
            resp.setCode(BaseEnum.PERSON_IMAGE_CODE_ERROR.getCode());
            resp.setMsg(BaseEnum.PERSON_IMAGE_CODE_ERROR.getMsg());
            return resp;
        }
        if(!Objects.equals(loginReq.getImageCode().toLowerCase(), imageCode.toLowerCase())){
            BaseResp resp = new BaseResp();
            resp.setCode(BaseEnum.PERSON_IMAGE_CODE_ERROR.getCode());
            resp.setMsg(BaseEnum.PERSON_IMAGE_CODE_ERROR.getMsg());
            return resp;
        }
        session.removeAttribute(SessionKeyConst.CAPTCHA_ADMIN_KEY);
        // 校验用户
        BaseResp resp = personService.doLogin(loginReq);
        if(resp.getCode() == BaseEnum.SUCCESS.getCode()){
            LoginVo loginVo = (LoginVo)resp.getData();
            Cookie token = new Cookie(SessionKeyConst.LOGIN_TOKEN, loginVo.getToken());
            token.setHttpOnly(true);
            token.setPath("/");
            token.setMaxAge(2*60*55*1000);
            response.addCookie(token);
            session.setAttribute(loginVo.getToken(), loginVo.getId());
            PersonVo personInfo = new PersonVo();
            personInfo.setId(loginVo.getId());
            personInfo.setLoginName(loginVo.getLoginName());
            personInfo.setState(loginVo.getState());
            session.setAttribute(SessionKeyConst.PERSON_INFO, personInfo);
            // 通过用户ID获取角色列表
            List<Long> roleIds = roleService.getRoleIdByPersonId(loginVo.getId());
            if(CollectionUtils.isNotEmpty(roleIds)){
                // 初始化用户数据
                session.setAttribute(SessionKeyConst.PERSON_ROLES, roleIds);
                List<PurviewVo> purviewList = purviewService.getPurviewByRoleIds(roleIds);
                PageResp<Map<String,Object>> menuResp = purviewService.queryMenu(purviewList);
                if(menuResp.getCode()==BaseEnum.SUCCESS.getCode()){
                    Map<String,Object> data = menuResp.getData();
                    session.setAttribute(SessionKeyConst.PERSON_PURES, data.get("purUrl"));
                    session.setAttribute(SessionKeyConst.PERSON_MENU, data.get("menu"));
                }
            }

            resp.setData(null);
            return resp;
        }
        resp.setData(null);
        return resp;
    }


    @RequestMapping(value = "/admin/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response){
        return login(request, response);
    }

    private void cleanLoginInfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for(Cookie cookie : cookies){
                if(Objects.equals(SessionKeyConst.LOGIN_TOKEN,cookie.getName())){
                    session.removeAttribute(cookie.getValue());
                    break;
                }
            }
        }
        session.removeAttribute(SessionKeyConst.PERSON_INFO);
        session.removeAttribute(SessionKeyConst.PERSON_ROLES);
        session.removeAttribute(SessionKeyConst.PERSON_PURES);
        session.removeAttribute(SessionKeyConst.PERSON_MENU);
    }
}
